package com.usian.skill.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.skill.common.Result;
import com.usian.skill.pojo.Goods;
import com.usian.skill.pojo.SkillUser;
import com.usian.skill.service.GoodsService;
import com.usian.skill.service.SkillUserService;
import com.usian.skill.vo.GoodsDetailVo;
import com.usian.skill.vo.GoodsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

@Controller
@RequestMapping("/goods")
public class GoodsController {

	@Autowired
	SkillUserService userService;
	
	@Autowired
	GoodsService goodsService;
	
	@Autowired
	ThymeleafViewResolver thymeleafViewResolver;
	
	@Autowired
	ApplicationContext applicationContext;
	
	/**
	 * QPS:1267 load:15 mysql
	 * 5000 * 10
	 * QPS:2884, load:5 
	 * */
	//商品列表
    @RequestMapping(value="/to_list")
    public String list(HttpServletRequest request, Model model, SkillUser user) {
		List<GoodsVo> goodsList = goodsService.listGoodsVo();
		model.addAttribute("goodsList", goodsList);
		return "goods_list";
    }
    //商品详情
    @RequestMapping(value="/detail/{goodsId}",produces="text/html")
    public String detail(HttpServletRequest request, HttpSession session, HttpServletResponse response, Model model, SkillUser user,
										@PathVariable("goodsId")long goodsId) {
		String us = (String) session.getAttribute("userId");
		GoodsVo vo = goodsService.getGoodsVoByGoodsId(goodsId);
		model.addAttribute("user",us);
		model.addAttribute("goods",vo);
		//将实际转换成毫秒值
		long startAt = vo.getStartDate().getTime();
		long endAt = vo.getEndDate().getTime();
		//获取系统的当前时间
		long now = System.currentTimeMillis();
		int miaoshaStatus = 0;
		int remainSeconds = 0;
		if(now < startAt ) {//秒杀还没开始，倒计时
			miaoshaStatus = 0;
			remainSeconds = (int)((startAt - now )/1000);
		}else  if(now > endAt){//秒杀已经结束
			miaoshaStatus = 2;
			remainSeconds = -1;
		}else {//秒杀进行中
			miaoshaStatus = 1;
			remainSeconds = 0;
		}
		model.addAttribute("miaoshaStatus",miaoshaStatus);
		model.addAttribute("remainSeconds",remainSeconds);
		return "goods_detail";
    }
    
    
}
